import logging
import random
# from com.sms import send_sms
from flask_mail import Message
from flask_socketio import SocketIO, emit
from flask import Blueprint, render_template, request, session, make_response, redirect, current_app
import re
from com.form import RegisterForm
from flask_jwt_extended import jwt_required, create_access_token, set_access_cookies, unset_access_cookies, \
    get_current_user
from com.gen_captcha import get_captcha_code_and_content
from extensions import db, redis_db, mail
from orms import UserORM

passport_bp = Blueprint('passport', __name__)

socketio = SocketIO()


@passport_bp.get('/register/')
def register_view():
    return render_template('register.html')


@passport_bp.get('/captcha/email/')
def send_email():
    # 1. 解析参数
    email = request.args.get('email')
    # 2. 校验手机号码
    pattern = r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$'  # 后端为什么还要再次校验？ 有没有可能请求不是前端发送过来的
    ret = re.match(pattern, email)
    if not ret:
        return {
            'message': '邮箱不符合格式',
            'code': -1
        }
    # 3. 发送短信验证码，并记录到后台
    code = random.choices('0123456789', k=4)
    message = Message('测试邮件', recipients=[f'{email}'])
    message.body = f'你的注册验证码是{"".join(code)}'
    mail.send(message)
    session['code'] = ''.join(code)
    session['email'] = email
    logging.warning(session['code'])
    print('-----------------------------------------------------')
    print(session['code'])
    print('-----------------------------------------------------')
    return {
        'code': 0,
        'message': '邮箱验证码发送成功,有效时间60秒'
    }


@passport_bp.post('/register/')
def register_post():
    form = request.form
    # 1. 校验短信验证码
    code = session.get('code')
    if code != form.get('vercode'):
        return {
            'code': -1,
            'message': '短信验证码错误'
        }
    # 2. 创建新用户
    user: UserORM = UserORM()
    user.nick_name = form.get('nick_name')
    user.password = form.get('password')
    user.email = form.get('email')
    # # 优化新增对象
    user.save()
    message = '注册账号成功，2s 中之后跳转到登录页'
    response = make_response({'message': message})
    response.headers['Content-Type'] = 'application/json'
    response.headers['Location'] = '/login'
    response.status_code = 302
    return response


# @socketio.on('message')
# def handle_message(msg):
#     emit('message', msg, broadcast=True)


@passport_bp.get('/login/')
def login():
    return render_template('login.html')


@passport_bp.get('/get_captcha/')
def get_captcha():
    image_code_uuid = request.args.get('image_code_uuid')
    # 需要将图片的唯一标识记录到Redis数据库
    text, image = get_captcha_code_and_content()
    session['code'] = text
    # 生成响应体对象
    response = make_response(image)
    # 设置response格式为图片
    response.content_type = 'image/png'
    print("image_code_uuid", image_code_uuid)
    #
    redis_db.store_chapter_image(image_code_uuid, text)
    return response


@passport_bp.post('/login/')
def login_post():
    data = request.json
    # 1. 校验图片验证码
    image_code_uuid = data.get('image_code_uuid')
    captcha_code = redis_db.get_chapter_image(image_code_uuid)
    captcha = data.get('captcha')
    print("---------------------------------------------")
    print(captcha_code)
    print(captcha)
    if captcha != captcha_code:
        return {
            'code': -1,
            'message': '图片验证码错误',
        }
    email = data.get('email')
    # 3. 查询数据
    try:
        user = UserORM.query.filter(UserORM.email == email).first()
    except Exception as e:
        current_app.logger.error(e)
        return {'status': 'error',
                'message': '查询用户出错'}
    if not user:
        return {
            'code': -1,
            'message': '用户不存在，请先注册',
        }
    pwd = data.get('password')
    if not user.check_passwd(pwd):
        return {
            'code': -1,
            'message': '用户密码错误',
        }
    # 校验都成功之后，需要发放 token
    session['user_id'] = user.id
    access_token = create_access_token(user)
    _next = request.args.get('next')
    response = make_response({
        'code': 0,
        'message': '登录成功',
        'next': _next if _next else '/',
        'access_token': access_token  # 返回给接口数据
    })
    # 设置到 cookie
    set_access_cookies(response, access_token)
    return response


@passport_bp.get('/logout/')
def logout():
    response = make_response(redirect('/'))
    unset_access_cookies(response)  # 删除cookie
    return response
